<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Picture, Van, Money } from '@element-plus/icons-vue'
import { findOrdersService, deliverOrderService, refundOrderService } from '../../api/merchant'
import { useMerchantStore } from '../../stores/merchant'

const router = useRouter()
const merchantStore = useMerchantStore()

// 订单列表数据
const orderList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索条件
const searchForm = ref<{
  status: number
  order_id: string
  name: string
}>({
  status: 0, // 默认查询所有状态订单
  order_id: '',
  name: ''
})

// 订单状态选项（后端从1开始）
const statusOptions = [
  { label: '全部', value: 0 },
  { label: '未发货', value: 1 },
  { label: '已发货', value: 2 },
  { label: '已到达', value: 3 },
  { label: '已收货', value: 4 },
  { label: '申请退款', value: 5 },
  { label: '拒绝退款', value: 6 },
  { label: '已退款', value: 7 }
]

// 订单状态映射（后端从1开始）
const statusMap: Record<number, { text: string; type: string }> = {
  1: { text: '未发货', type: 'warning' },
  2: { text: '已发货', type: 'primary' },
  3: { text: '已到达', type: 'success' },
  4: { text: '已收货', type: 'success' },
  5: { text: '申请退款', type: 'warning' },
  6: { text: '拒绝退款', type: 'danger' },
  7: { text: '已退款', type: 'info' }
}

// 格式化规格信息
const formatSpec = (spec: string): string => {
  try {
    const specObj = JSON.parse(spec)
    return Object.entries(specObj)
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ')
  } catch (error) {
    return spec
  }
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const res: any = await findOrdersService(
      searchForm.value.status === 0 ? undefined : searchForm.value.status,
      searchForm.value.order_id || undefined,
      searchForm.value.name || undefined,
      currentPage.value,
      pageSize.value
    )
    if (res.code === 0) {
      orderList.value = res.data.items || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索订单
const handleSearch = () => {
  currentPage.value = 1
  loadOrders()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    status: 0,
    order_id: '',
    name: ''
  }
  currentPage.value = 1
  loadOrders()
}

// 状态改变时自动搜索
const handleStatusChange = () => {
  currentPage.value = 1
  loadOrders()
}

// 页码改变
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadOrders()
}

// 发货操作
const shipOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要将订单 ${order.orderId} 标记为已发货吗？`,
      '发货确认',
      {
        confirmButtonText: '确定发货',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用发货接口
    const res: any = await deliverOrderService(order.id)
    if (res.code === 0) {
      ElMessage.success('发货成功！')
      // 刷新订单列表
      loadOrders()
    } else {
      ElMessage.error(res.message || '发货失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('发货失败:', error)
      ElMessage.error('发货失败，请稍后重试')
    }
  }
}

// 退款操作
const refundOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要同意订单 ${order.orderId} 的退款申请吗？`,
      '退款确认',
      {
        confirmButtonText: '同意退款',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用退款接口
    const res: any = await refundOrderService(order.id)
    if (res.code === 0) {
      ElMessage.success('退款处理成功！')
      // 刷新订单列表
      loadOrders()
    } else {
      ElMessage.error(res.message || '退款失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('退款失败:', error)
      ElMessage.error('退款失败，请稍后重试')
    }
  }
}

onMounted(() => {
  // 检查商家是否已登录
  if (!merchantStore.isLoggedIn || !merchantStore.merchantToken) {
    ElMessage.warning('请先登录商家账号')
    router.push('/merchant/auth')
    return
  }
  
  loadOrders()
})
</script>

<template>
  <div class="merchant-orders">
    <!-- 头部 -->
    <div class="page-header">
      <h2>订单管理</h2>
      <div class="header-actions">
        <el-button @click="router.push('/merchant/dashboard')">返回商品管理</el-button>
        <el-button @click="router.push('/layout')">返回主页</el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单状态">
          <el-select 
            v-model="searchForm.status" 
            style="width: 120px;"
            @change="handleStatusChange"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单ID">
          <el-input
            v-model="searchForm.order_id"
            placeholder="请输入订单ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单表格 -->
    <el-table
      :data="orderList"
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="orderId" label="订单ID" width="200" />
      <el-table-column label="商品信息" min-width="300">
        <template #default="{ row }">
          <div class="product-info">
            <div class="product-image" v-if="row.image">
              <el-image
                :src="row.image"
                :alt="row.name"
                fit="cover"
                style="width: 60px; height: 60px; border-radius: 4px;"
                :preview-src-list="[row.image]"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="product-details">
              <div class="product-name">{{ row.name }}</div>
              <div class="product-spec" v-if="row.spec">
                规格：{{ formatSpec(row.spec) }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="数量" width="80" />
      <el-table-column prop="price" label="单价" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column label="总价" width="120">
        <template #default="{ row }">
          <span class="total-price">¥{{ (row.price * row.num).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusMap[row.status]?.type">
            {{ statusMap[row.status]?.text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <template v-if="row.status === 7">
            <span class="no-action">暂无可执行操作</span>
          </template>
          <template v-else>
            <el-button 
              v-if="row.status === 1" 
              type="success" 
              size="small"
              :icon="Van"
              @click="shipOrder(row)"
            >
              发货
            </el-button>
            <el-button 
              type="warning" 
              size="small"
              :icon="Money"
              @click="refundOrder(row)"
            >
              退款
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
        :prev-text="'上一页'"
        :next-text="'下一页'"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.merchant-orders {
  padding: 2rem;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 1.5rem 2rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
  }

  .header-actions {
    display: flex;
    gap: 0.5rem;
  }
}

.search-bar {
  background: white;
  padding: 1.5rem 2rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 1.5rem;
  display: flex;
  justify-content: center;
}

// 商品信息样式
.product-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;

  .product-image {
    flex-shrink: 0;

    .image-slot {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      background: #f5f7fa;
      color: #909399;
      font-size: 1.5rem;
      border-radius: 4px;
    }
  }

  .product-details {
    flex: 1;
    min-width: 0;

    .product-name {
      font-size: 0.9rem;
      color: #303133;
      font-weight: 500;
      line-height: 1.4;
      margin-bottom: 0.25rem;
      word-break: break-word;
    }

    .product-spec {
      font-size: 0.8rem;
      color: #909399;
      line-height: 1.2;
    }
  }
}

.total-price {
  color: #e74c3c;
  font-weight: 600;
}

.no-action {
  color: #909399;
  font-size: 0.85rem;
  padding: 0.5rem;
  display: inline-block;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>
